import React, {Component} from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TouchableHighlight,
  SafeAreaView,
} from 'react-native';
import Modal from 'react-native-modal';
import QList from './QList';
import {unionBy} from 'lodash';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export default class FetchPicker extends Component {
  constructor(props) {
    super(props);
  }
  async componentDidMount() {
    this.updateValue(this.props);
  }
  componentWillUnmount() {
    this.unmonted = true;
  }
  state = {
    show: false,
    lazyItems: [],
    items: [],
    multiple: false,
  };
  hide() {
    this.setState({
      show: false,
    });
  }
  updateValue(props) {
    const {value, multiple, nativeObject} = props;
    const {items, lazyItems} = this.state;

    if (multiple) {
      const values = value || [];
      if (values && Array.isArray(values)) {
        const allItems = [...unionBy(nativeObject, lazyItems, 'value')];
        // console.log(value, allItems, lazyItems);
        const tmpItems = values.map((ele) =>
          allItems.find((iEle) => ele === (iEle && iEle.value)),
        );
        this.setState({
          lazyItems: [...tmpItems],
          items: [...tmpItems],
        });
      }
    } else {
      if (!items.find((ele) => (ele && ele.value) === value)) {
        this.setState({
          lazyItems: [nativeObject],
          items: [nativeObject, ...lazyItems],
        });
      }
    }
  }

  UNSAFE_componentWillReceiveProps(props) {
    this.updateValue(props);
  }
  renderItem(info) {
    const {item} = info;
    const {multiple} = this.props;
    const {lazyItems} = this.state;
    const active = !!lazyItems.find((ele) => (ele && ele.value) === item.value);
    return (
      <TouchableHighlight
        underlayColor="#ddd"
        style={[styles.item, active && styles.activeItem]}
        onPress={() => {
          if (multiple) {
            const tmpItems = [...lazyItems];
            const itemIndex = lazyItems.findIndex(
              (ele) => (ele && ele.value) === item.value,
            );
            console.log(itemIndex);
            if (itemIndex === -1) {
              tmpItems.push(item);
            } else {
              tmpItems.splice(itemIndex, 1);
            }
            this.setState({
              lazyItems: tmpItems,
            });
          } else {
            this.setState(
              {
                lazyItems: [item],
                show: false,
              },
              this.confirm.bind(this),
            );
          }
        }}>
        <>
          <Text style={[active && styles.activeText]}>{item.label}</Text>
          {active && (
            <Icon
              name={multiple ? 'check-circle' : 'check'}
              color="#1867c0"
              size={20}
            />
          )}
        </>
      </TouchableHighlight>
    );
  }

  getActiveItems() {
    const {items = []} = this.state;
    return items;
  }
  getActiveItemValues() {
    const {multiple} = this.props;
    const activeItems = this.getActiveItems() || [];
    const activeItemValues = activeItems.map((ele) => ele && ele.value);
    return multiple ? activeItemValues : activeItemValues[0];
  }
  confirm() {
    const {onValueChange} = this.props;
    const {lazyItems} = this.state;
    this.hide();
    this.setState(
      {
        items: lazyItems,
      },
      () => {
        onValueChange && onValueChange(this.getActiveItemValues());
      },
    );
  }
  render() {
    const {value, fetch, disabled, onValueChange} = this.props;

    const activeItems = this.getActiveItems();

    return (
      <>
        <View style={styles.container}>
          <TouchableOpacity
            disabled={disabled}
            onPress={() => {
              this.setState({
                show: true,
              });
            }}
            style={styles.input}>
            {value ? (
              <Text>
                {activeItems &&
                  activeItems.map((ele) => ele && ele.label).join(',')}
              </Text>
            ) : (
              <Text>請選擇</Text>
            )}
          </TouchableOpacity>
          <TouchableOpacity
            disabled={disabled}
            onPress={onValueChange && onValueChange.bind(this, null)}
            style={styles.clearContainer}>
            <Icon name="close-circle" size={15} />
          </TouchableOpacity>
        </View>

        <Modal
          isVisible={this.state.show}
          style={[styles.modal]}
          onPress={this.hide.bind(this)}>
          <SafeAreaView style={styles.content}>
            <View style={styles.actionBar}>
              <TouchableOpacity>
                <Text style={styles.actionBtnText}>CANCEL</Text>
              </TouchableOpacity>
              <Text>Picker</Text>
              <TouchableOpacity onPress={this.confirm.bind(this)}>
                <Text style={styles.actionBtnText}>OK</Text>
              </TouchableOpacity>
            </View>
            <QList fetch={fetch} renderItem={this.renderItem.bind(this)} />
          </SafeAreaView>
        </Modal>
      </>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  input: {
    flex: 1,
  },
  modal: {
    justifyContent: 'flex-end',
    margin: 0,
  },
  content: {
    backgroundColor: '#fff',
    maxHeight: 400,
  },
  actionBtnText: {
    color: '#1867c0',
    fontWeight: '500',
  },
  actionBar: {
    height: 60,
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 10,
  },
  item: {
    height: 44,
    marginVertical: 1,
    paddingLeft: 10,
    paddingRight: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    borderTopRightRadius: 22,
    borderBottomRightRadius: 22,
    marginRight: 10,
  },
  activeItem: {
    backgroundColor: '#b3d4fc',
  },
  activeText: {
    color: '#1867c0',
  },
  checkboxContainer: {
    margin: 0,
  },
  clearContainer: {
    padding: 5,
  },
});
